package com.group525.cloudef.service.user.impl;

import com.group525.cloudef.common.CommonResult;
import com.group525.cloudef.entity.user.UImage;
import com.group525.cloudef.mapper.user.UImageMapper;
import com.group525.cloudef.service.user.UImageService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.group525.cloudef.utils.Log;
import com.group525.cloudef.utils.PreProcess;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.naming.ldap.PagedResultsControl;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author group525
 * @since 2023-05-24
 */
@Service
public class UImageServiceImpl extends ServiceImpl<UImageMapper, UImage> implements UImageService {
    @Resource
    UImageMapper ImageMapper;
    @Resource
    Log log;
    @Resource
    PreProcess preProcess;

    @Override
    public List<UImage> getImage(Long user_id){
        //读取该患者的影像数据
        List<UImage> imageList = ImageMapper.getImage(user_id);
        //foreach遍历每条数据
        imageList.forEach(UImage -> {
            log.debug("遍历:",UImage);
            //获取url地址
            String imageUrl = UImage.getImage();
            //获取imageId（作为图像名上传）
            Long imageId = UImage.getImageNo();
            //判断是否经过预处理
            Integer pre = UImage.getPreprocess();
            //如果未经预处理，调用预处理
            if(pre == 0){
                //1.首先根据对应的url地址从OSS服务器下载图片（test.jpg）
                boolean flag = preProcess.download(imageUrl);
                log.debug("下载保存:",flag);
                //2.opencv调用下载到本地的图片（test.jpg），经预处理后生成output.jpg
                try {
                    preProcess.testOpencv();
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
                //3.将预处理后的图片上传至OSS，并获取新的url地址
                String urlUpdate = preProcess.upload(imageId);
                //4.更新此条数据中的url和preprocess
                UImage.setImage(urlUpdate);
                UImage.setPreprocess(1);
                log.debug("处理后:",UImage);
                //5.调用update函数，更新数据库中对应的url地址，并将preprocess设为1
                ImageMapper.updateImage(urlUpdate, imageId);
            }
        });

        return imageList;
    }

    @Override
    public CommonResult<?> CountImageType() {
        return CommonResult.success(null,ImageMapper.CountImageType());
    }
}
